package laba8;

import interfaces.task8.SerializableUtils;
import java.io.InputStream;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

/**
 *
 * @author yakimovich
 */
public class SerializableUtilsImpl
        implements SerializableUtils {

    /**
     * The method serializes the specified object
     * to the specified OutputStream.
     * @param out the specified OutputStream
     * @param o object to be serialized
     */
    @Override
    public void serialize(OutputStream out, Object o) {
        ObjectOutputStream sout;

        if (out == null || o == null) {
            throw new NullPointerException();
        }

        try {
            if (!(o instanceof Serializable)) {
                throw new NotSerializableException();
            }
            sout = new ObjectOutputStream(out);
            sout.writeObject(o);
            sout.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * The method deserelizes object from the specified InputStream.
     * @param in the specified InputStream.
     * @return deserialized object
     */
    @Override
    public Object deserialize(InputStream in) {

        if (in == null) {
            throw new NullPointerException();
        }

        Object result = null;
        try {
            ObjectInputStream sin = new ObjectInputStream(in);
            result = sin.readObject();
            sin.close();
        } catch (Exception e) {
            System.out.println(e);

        }
        return result;
    }
}
